<script setup lang="js">
import { ref, watch } from 'vue';
import { createResource, updateResource } from "@/api/resource.js";
import {ElMessage} from "element-plus";

const props = defineProps({
  isEdit: Boolean,
  resourceForm: Object,
  categoryOptions: Object,
});

const emits = defineEmits(['close'],['refresh']);

const formRef = ref('');

const handleSubmit = () => {
  if (props.isEdit) {
    let id = props.resourceForm.categoryId;
    updateResource(id, props.resourceForm).then((res) => {
      ElMessage.warning(res.data.message)
      ElMessage.success('修改成功')
      console.log(props.resourceForm);
      emits('close');
      emits('refresh');
    });
  } else {
    createResource(formRef.value).then((res) => {
      ElMessage.warning(res.data.message)
      ElMessage.success('添加成功！')
      console.log(props.resourceForm);
      emits('close');
      emits('refresh');
    });
  }
}

const handleCancel = () => {
  emits('close');
}

watch(
    () => props.resourceForm,
    (newVal, oldVal) => {
      if (newVal.id !== oldVal.id) {
        formRef.value = newVal;
      }
    },
);
</script>

<template>
  <el-dialog
      :title="isEdit ? '编辑资源：' : '添加资源：'"
      width="30%"
      draggable
  >
    <el-form ref="formRef" :model="resourceForm" label-width="100px">
      <el-form-item label="资源名称：">
        <el-input v-model="resourceForm.name" placeholder="资源名称" class="input-width" clearable></el-input>
      </el-form-item>
      <el-form-item label="资源路径：">
        <el-input v-model="resourceForm.url" placeholder="资源路径" class="input-width" clearable></el-input>
      </el-form-item>
      <el-form-item label="资源分类：">
        <el-select v-model="resourceForm.categoryId" placeholder="请选择分类" class="input-width" clearable>
          <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述：">
        <el-input v-model="resourceForm.description" type="textarea" placeholder="资源描述"
                  class="input-width"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.input-width {
  width: 400px;
}
</style>
